package com.yssoft.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.yssoft.entity.core.*;
import com.yssoft.entity.production.TLabels;
import com.yssoft.entity.purchase.TPurchaseAtt;
import com.yssoft.entity.purchase.TPurchaseInfo;
import com.yssoft.entity.sales.TSalesOrder;
import com.yssoft.service.IndexService;
import com.yssoft.service.core.AreaService;
import com.yssoft.service.core.EnterpriseService;
import com.yssoft.service.sales.SaleOrderService;
import com.yssoft.utils.UserHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Controller
@Api(value = "index", description = "首页控制")
public class IndexController extends BaseController {

    @Resource
    private EnterpriseService enterpriseService;

    @Resource
    private AreaService areaService;

    @Resource
    private IndexService indexService;
    @Resource
    private SaleOrderService saleOrderService;


    @RequestMapping("/op_{oper}_{id}")
    @ApiOperation(value = "根据oper与id转发到指定的地址", httpMethod = "GET")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "请求成功"),
            @ApiResponse(code = 404, message = "地址错误"),
            @ApiResponse(code = 500, message = "系统错误,请联系管理人员")
    })
    public String op(@PathVariable String oper, @PathVariable Integer id, Model model) {

        return "404";
    }

    /***
     * 进入到首页
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("index")
    public String index(Model model, HttpServletRequest request) {
        model.addAttribute("userName", UserHelper.getCurrentUser().getName());
        //model.addAttribute("list",menuService.listTree(SessionUtil.getSession()));
        return "index";
    }

    /**
     * 控制台
     * add by 王维鑫 20180518
     *
     * @param area 地区
     * @update 20180614
     * @updateContent 添加查询首页的信息
     */
    @RequestMapping("console")
    public String console(Model model, HttpServletRequest request, String area) {
        Integer enterpriseId = UserHelper.getCurrentCompanyId();
        //查询子地区生成地图中的tree
        List<Map<String, Object>> areaList = areaService.queryChildren("230100");
        model.addAttribute("areaList", JSONObject.toJSON(areaList));

        //查询该地区及子地区下面的企业信息
        List<TEnterprise> entList = enterpriseService.selectAll(area);
        model.addAttribute("entCount", entList.size());
        //查询销售数量
        int count = saleOrderService.querySalesOrderCount(enterpriseId);
        model.addAttribute("salesOrderCount", count);
        //查询生产商数量


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
        int currentMonthEntCount = 0;
        String currentMonth = simpleDateFormat.format(new Date());
        for (TEnterprise tEnterprise : entList) {

            String entCreateMonth = simpleDateFormat.format(tEnterprise.getCreateTime());
            //判断企业月份和当前月份是否相同
            if (currentMonth.equals(entCreateMonth)) {
                currentMonthEntCount++;
            }
        }
        model.addAttribute("currentMonthEntCount", currentMonthEntCount);

        if (entList != null && entList.size() > 0) {


            //查询当前这些企业的标签信息
            Map<String, Object> labelsCount = indexService.selectCurrentEntLables(entList);
            model.addAttribute("labelCount", labelsCount.get("shu"));
            //查询当前企业当前月份的标签
            Map<String, Object> currentDateLabelsCount = indexService.selectCurrentEntCurrentDateLables(entList, currentMonth);
            model.addAttribute("currentMonthLabelCount", currentDateLabelsCount.get("shu"));

            //查询当前这些企业的产品数量
            Map<String, Object> productsCount = indexService.selectCurrentEntProductCount(entList);
            Map<String, Object> productsCurrentDateCount = indexService.selectCurrentEntProductCurrentDateCount(entList, currentMonth);
            model.addAttribute("productsCount", productsCount.get("shu"));
            model.addAttribute("currentMonthProductCount", productsCurrentDateCount.get("shu"));

            //查询当前查询出的企业的在册人数
            Map<String, Object> personnalList = indexService.selectCurrentEntPersonnalCount(entList);
            model.addAttribute("personnalCount", personnalList.get("shu"));
            Map<String, Object> currentMonthPersonnalCount = indexService.selectCurrentEntPersonnalCurrentDateCount(entList, currentMonth);
            model.addAttribute("currentMonthPersonnalCount", currentMonthPersonnalCount.get("shu"));


            //查询当前查询出的企业的注册账号
            List<TAccounts> accountList = indexService.selectCurrentEntAccount(entList);
            model.addAttribute("accountCount", accountList.size());
            int currentMonthAccountCount = 0;
            for (TAccounts account : accountList) {
                String labelCreateMonth = simpleDateFormat.format(account.getCreateTime());
                //判断企业月份和当前月份是否相同
                if (currentMonth.equals(labelCreateMonth)) {
                    currentMonthAccountCount++;
                }
            }
            model.addAttribute("currentMonthAccountCount", currentMonthAccountCount);


            //查询企业的(进五个月)销售订单个数，按照日期分割
            List<Map<String, Object>> salesOrdersList = indexService.selectCurrentEntSalesOrder(entList);
            SimpleDateFormat s = new SimpleDateFormat("yyyy-MM");
            if (salesOrdersList.size() >= 5) {
                JSONArray jsonArray = new JSONArray();
                for (Map<String, Object> salesOrder : salesOrdersList.subList(0, 5)) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("num", salesOrder.get("num"));
                    try {
                        jsonObject.put("create_time", s.format(s.parse(salesOrder.get("create_time") + "")));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    jsonArray.add(jsonObject);
                }
                model.addAttribute("salesOrdersCountList", jsonArray);
            } else {
                JSONArray jsonArray = new JSONArray();
                for (Map<String, Object> salesOrder : salesOrdersList) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("num", salesOrder.get("num"));
                    try {
                        jsonObject.put("create_time", s.format(s.parse(salesOrder.get("create_time") + "")));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    jsonArray.add(jsonObject);
                }
                model.addAttribute("salesOrdersCountList", jsonArray);
            }


            //查询企业的(进五个月)采购订单个数，按照日期分割
            List<Map<String, Object>> purchaseInfoList = indexService.selectCurrentEntPurchaseOrder(entList);
            if (purchaseInfoList.size() >= 5) {
                JSONArray jsonArray = new JSONArray();
                for (Map<String, Object> purchase : purchaseInfoList.subList(0, 5)) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("num", purchase.get("num"));
                    try {
                        jsonObject.put("create_time", s.format(s.parse(purchase.get("create_time") + "")));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    jsonArray.add(jsonObject);
                }
                model.addAttribute("purchaseInfoCountList", jsonArray);
            } else {
                JSONArray jsonArray = new JSONArray();
                for (Map<String, Object> purchase : purchaseInfoList) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("num", purchase.get("num"));
                    try {
                        jsonObject.put("create_time", s.format(s.parse(purchase.get("create_time") + "")));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    jsonArray.add(jsonObject);
                }
                model.addAttribute("purchaseInfoCountList", jsonArray);
            }
        } else {
            model.addAttribute("labelCount", 0);
            model.addAttribute("currentMonthLabelCount", 0);
            model.addAttribute("productsCount", 0);
            model.addAttribute("currentMonthProductCount", 0);
            model.addAttribute("personnalCount", 0);
            model.addAttribute("currentMonthPersonnalCount", 0);
            model.addAttribute("accountCount", 0);
            model.addAttribute("currentMonthAccountCount", 0);
            model.addAttribute("salesOrdersCountList", new JSONArray());
            model.addAttribute("purchaseInfoCountList", new JSONArray());
        }
        return "consoleHrb";
    }

    @RequestMapping("selectCompanyByArea")
    public String selectCompanyByArea(String area, Model model) {
        //查询该地区及子地区下面的企业信息``````````````````````````````````````````````````````````````````````````````
        // List<TEnterprise> entList = enterpriseService.selectAll(area);
        // System.out.println(entList);
        model.addAttribute("area", area);
        return "companyList";
    }


    /**
     * @param page
     * @param limit
     * @param area
     * @return JSONObject
     * @方法名称: findTraceProcessPage
     * @功能描述: 获取溯源流程列表页面
     * @作者: 洪丰
     * @创建时间:2018年5月23日 下午4:41:37
     */
    @RequestMapping("/findPage")
    @ResponseBody
    public JSONObject findPage(@RequestParam(name = "page", defaultValue = "0") int page, @RequestParam(name = "limit", defaultValue = "10") int limit, String area, String name) {
        JSONObject jsonObject = enterpriseService.selectAllPage(page, limit, area, name);
        return jsonObject;
    }
}
